package servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;



public class UploadImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public UploadImageServlet() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// get file on disk
		DiskFileItemFactory factory=new DiskFileItemFactory(20*1024, new File("C:/Users/WUJA11/Downloads/foobar.jpg"));
		ServletFileUpload upload=new ServletFileUpload(factory);
		// limit the upload file size
		upload.setSizeMax(80*1024);
		
		try {
			List<FileItem> items= upload.parseRequest(request);
			for(FileItem item:items){
				// other field in the form
				if(item.isFormField()){
					System.out.println(item.getFieldName()+"..."+item.getString());
				}
				else{ // the upload file in the form
					System.out.println(item.getName()+"..."+item.getSize());
					InputStream fin=item.getInputStream();
					OutputStream fout = new FileOutputStream(new File("C:/Users/WUJA11/Downloads/1.jpg"));
					// set buffer
					byte[] buf=new byte[512];
					int len=0;
					while((len=fin.read(buf))!=-1){
						fout.write(buf, 0, len);
					}
					fout.close();
					fin.close();
 				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

}
